package com.beetobe.callib.event;

import java.io.IOException;

import com.beetobe.callib.CalendarLibHelper;
import com.beetobe.callib.test.EventListActivity;
import com.google.api.services.calendar.model.Event;
import com.google.api.services.calendar.model.Events;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.os.AsyncTask;

public class AsyncLoadEvents extends AsyncTask<Void, Void, Void> {

	private final EventListActivity EventListActivity;
	private final ProgressDialog dialog;
	private com.google.api.services.calendar.Calendar client;
	private String calendarId;

	public AsyncLoadEvents(EventListActivity EventListActivity, String calendarId) {
		this.EventListActivity = EventListActivity;
		this.calendarId = calendarId;
		client = CalendarLibHelper.client;
		dialog = new ProgressDialog(EventListActivity);
	}

	@Override
	protected void onPreExecute() {
		dialog.setMessage("Loading events...");
		dialog.show();
	}

	@SuppressLint({ "ParserError", "NewApi" })
	@Override
	protected Void doInBackground(Void... arg0) {
		try {
			EventListActivity.eventList.clear();
			
			com.google.api.services.calendar.model.Calendar calendar = client
					.calendars().get(calendarId).execute();
			Events events = client.events().list(calendar.getId()).execute();
			while (true) {
				for (Event event : events.getItems()) {
					EventInfo info = new EventInfo(event.getId(),
							event.getSummary());
					EventListActivity.eventList.add(info);
				}
				String pageToken = events.getNextPageToken();
				if (pageToken != null && !pageToken.isEmpty()) {
					events = client.events().list(calendarId)
							.setPageToken(pageToken).execute();
				} else {
					break;
				}
			}
		} catch (IOException e) {
			EventListActivity.handleGoogleException(e);
		} finally {
			EventListActivity.onRequestCompleted();
		}
		return null;
	}

	@Override
	protected void onPostExecute(Void result) {
		dialog.dismiss();
		EventListActivity.refresh();
	}

}
